<?php

namespace app\common\command\task;

use app\common\enum\EsSearchKeyEnum;
use app\common\model\Course;
use Elastic\Elasticsearch\Client;

/**
 * php think cron indexCourseSearchData
 */
class IndexEsCourseSearchData
{
    /**
     * client
     * @var Client
     */
    protected ?Client $client = null;

    /**
     * invoke
     * @throws
     */
    public function invoke()
    {
        //  执行更新
        $this->execute();
    }

    /**
     * executeItem
     * @throws
     */
    private function execute()
    {
        // 获取Es客户端
        $this->client = getEsClient();

        // 索引所有课程
        $this->indexAllCourse();

        // 检查所有课程索引(手动删除的行为)
        $this->checkAllCourseIndex();
    }

    /**
     * 检查所有课程索引
     * @return void
     * @throws
     */
    private function checkAllCourseIndex()
    {

        // 构建查询
        $params = [
            'index' => getEsIndex(EsSearchKeyEnum::COURSE_KEY),
            'body' => [
                'query' => [
                    'match_all' => new \stdClass()
                ]
            ],
            'scroll' => '1m'
        ];
        $response = $this->client->search($params);

        // 获取滚动 ID
        $scroll_id = $response['_scroll_id'];

        // 循环获取数据
        do {
            $params = [
                'body' => [
                    'scroll' => '1m', // 保持滚动上下文
                    'scroll_id' => $scroll_id // 滚动 ID
                ]
            ];

            // 获取下一页数据
            $response = $this->client->scroll($params);

            // 获取数据
            $results = $response['hits']['hits'];

            // 处理数据
            foreach ($results as $result) {
                // 提取参数
                $course_id = $result['_id'];

                // 查询课程是否存在
                $where = [
                    'id' => $result['_id']
                ];
                $count = app(Course::class)->where($where)->count();
                if (!$count) {
                    // 不存在的课程进行删除
                    $response = $this->client->delete([
                        'index' => getEsIndex(EsSearchKeyEnum::COURSE_KEY),
                        'id' => $course_id
                    ]);
                }
            }
            $scroll_id = $response['_scroll_id'];
        } while (count($results) > 0);
        $this->client->clearScroll(['body' => ['scroll_id' => [$scroll_id]]]);
    }

    /**
     * 索引全部课程
     * @return void
     * @throws
     */
    private function indexAllCourse()
    {
        // 查询条件
        $where = [
            ['status', '=', 1],
            ['user_id', '=', 0],
        ];
        $allCourseList = app(Course::class)->where($where)->select();

        // 循环更新
        foreach ($allCourseList as $course) {
            // 添加到ES
            $content = $course['name'];
            if (!empty($course['code'])) {
                $content = $content . $course['code'];
            }

            // 添加
            $params = [
                'index' => getEsIndex(EsSearchKeyEnum::COURSE_KEY),
                'id' => $course['id'],
                'body' => ['id' => $course['id'], 'content' => $content]
            ];
            $response = $this->client->index($params);
            //dump($response);
        }
    }
}